package com.kakavr.alipay.service;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.kakavr.alipay.dao.IAlipayDao;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.base.service.BaseService;
import com.kakavr.pay.constant.ALiPayConstant;
import com.kakavr.pay.constant.PayConstant;
import com.kakavr.pay.constant.WxConstant;
import com.kakavr.pay.util.AlipayUtil;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.user.service.IUserRechargeService;
import com.kakavr.util.ConvertUtils;

@Service
public class AlipayService extends BaseService implements IAlipayService {
	@Resource
	private IAlipayDao alipayDao;
	@Resource
	private IUserRechargeService userRechargeService;

	@Override
	public String addAlipayLog(Map<String, Object> map) {
		// 返回支付需要内容
		AlipayClient alipayClient = AlipayUtil.getAlipayClient();
		// 设置请求参数
		AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
		request.setNotifyUrl(ALiPayConstant.getAlipayNotifyUrl());// 在公共参数中设置回跳和通知地址
		request.setReturnUrl(ALiPayConstant.getAlipayReturnUrl());
		request.setBizContent("{\"out_trade_no\":\"" + map.get("tradeno") + "\"," 
				+ "\"total_amount\":\"" + map.get("amount") + "\","
				+ "\"subject\":\"" + WxConstant.BODY + "\"," 
				+ "\"body\":\"" + WxConstant.BODY + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		String result = null;
		try {
			result = alipayClient.pageExecute(request).getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
			error("初始化支付宝支付时出错，错误信息：" + e);
			throw new ValidateParamException(MsgConstants.MSG_CODE_1001,
					"初始化支付宝支付时出错");
		}
		map.put("requestinfo", request.getBizContent());
		alipayDao.insertAlipayLog(map);
		return result;
	}

	@Override
	public boolean updateAlipayLogByNotify(Map<String, String> map) {
		String outTradeNo = map.get("out_trade_no");
		if (PayConstant.isHaveCode(outTradeNo)) {
			info("支付宝支付后端响应重复");
			return true;
		}
		String notifyInfo = ConvertUtils.POToJson(map);
		map.put("notifyInfo", notifyInfo);
		if ("TRADE_SUCCESS".equals(map.get("trade_status"))) {
			Map<String, Object> logMap = alipayDao
					.selectAlipayByOutTradeNo(map);
			if (null == logMap || logMap.isEmpty()) {
				error("支付宝支付后端未取到支付的具体信息，参数为：" + notifyInfo);
				return false;
			}
			int status = (int) logMap.get("status");
			if (status < 99) {
				info("支付宝已通知，支付宝支付状态status=" + status);
				return true;
			}
			userRechargeService.updateUserRechargeByPay(logMap.get("userId"),
					outTradeNo, logMap.get("totalfee"), 0);
			map.put("status", "1");
		} else {
			map.put("status", "2");
		}
		alipayDao.updateAlipayLog(map);
		return true;
	}

	@Override
	public boolean checkZFBSign(Map<String, String> map) throws Exception {
		return AlipaySignature.rsaCheckV1(map,
				ALiPayConstant.getAlipayPublicKey(),
				ALiPayConstant.ALI_INPUT_CHARSET, ALiPayConstant.RSA2);
	}

}
